//variable
var orgArrayMs;

//create function
function createTextBox(name, value, readOnly) {
	var txtBox = jQuery("<input type=\"text\"/>");
	txtBox.attr("name", name);
	txtBox.attr("id", name);
	txtBox.val(value);
	if(readOnly)
		txtBox.attr("readonly", "readonly");
	return txtBox;
}

function creatHidden(name, value) {
	var hidden = jQuery("<input type=\"hidden\" />");
	hidden.attr("name", name);
	hidden.attr("id" ,name);
	hidden.val(value);
	return hidden;
}
//check function
function checkName(event) {
	var inputName = jQuery(this).val();
	var errTag = jQuery("span#err_"+ jQuery(this).attr("name"));
	if(inputName == null || inputName.length < 1 || inputName.length > 50)
		errTag.text("Incorrect input");
	else {
		errTag.text("");
	}
}

function checkMark(event) {
	var inputMark = jQuery(this).val();
	var errTag = jQuery("span#err_" + jQuery(this).attr("name"));
	if(inputMark == null || isNaN(inputMark) || inputMark <= -1000 || inputMark >= 1000)
		errTag.text("Incorrect input");
	else {
		if(inputMark == "")
			jQuery(this).val(0);
		else {
			var mark = parseFloat(inputMark);
			jQuery(this).val(mark.toFixed(2));
		}
		errTag.text("");
	}
}

//clone array
function cloneArray(arrMs) {
	if(arrMs == null || arrMs.length < 1)
		return;
	
	var newArr = new Array();
	for(var i = 0; i < arrMs.length; i++) {
		newArr[i] = new Object();
		newArr[i].order = arrMs[i].order;
		newArr[i].name = arrMs[i].name;
		newArr[i].criteria = arrMs[i].criteria;
		newArr[i].mark = arrMs[i].mark;
	}
	return newArr;
}

//form function
function restartForm() {
	arrayMs = cloneArray(orgArrayMs);
	drawTable();
}

function saveToArr() {
	//get marks
	var msVal = jQuery("input[name^=\"mark_\"]");
	jQuery.each(msVal, function() {
		var mark = jQuery(this).val();
		if(mark != null && !isNaN(mark))
			mark = parseFloat(mark).toFixed(2);

		var index = parseInt(jQuery(this).attr("name").substring(5)) - 1;
		if(index >= 0 && index < arrayMs.length)
			arrayMs[index].mark = mark;
	});
	
	//get name
	msVal = jQuery("input[name^=\"name_\"]");
	jQuery.each(msVal, function() {
		var name = jQuery(this).val();
		var index = parseInt(jQuery(this).attr("name").substring(5)) - 1;
		if(index >= 0 && index < arrayMs.length)
			arrayMs[index].name = name;
	});
	//get criteria
	msVal = jQuery("textarea[name^=\"criteria_\"]");
	jQuery.each(msVal, function() {
		var criteria = jQuery(this).val();
		var index = parseInt(jQuery(this).attr("name").substring(9)) - 1;
		if(index >= 0 && index < arrayMs.length)
			arrayMs[index].criteria = criteria;
	});
}

function addBeforeThis(index) {
	saveToArr();
	var ms = new Object();
	ms.order = index;
	ms.name = "New Marking Scheme";
	ms.criteria = "";
	ms.mark = 0;
	arrayMs.splice(index, 0, ms);
	
	resetOrder();
	drawTable();
}

function addAtEnd() {
	saveToArr();
	var ms = new Object();
	ms.order = 1;
	ms.name = "New Marking Scheme";
	ms.criteria = "";
	ms.mark = 0;
	arrayMs.push(ms);
	
	resetOrder();
	drawTable();
}

function removeThis(index) {
	if(arrayMs.length < 2)
		return;
	saveToArr();
	
	arrayMs.splice(index, 1);
	resetOrder();
	drawTable();
}

function submitMs() {
	//put data into java array
	saveToArr();	
	
	//check data is correct
	var errRow = checkAll();
	if(errRow > 0) {
		//if incorrect data, alert message
		alert('Incorrect input on sheme!\r\nOrder:'+ errRow);
		return;
	}
	
	//create form to post back
	var submitForm = jQuery("<form action=\"f_confirm_ms.jsp\" method='post'/>").appendTo('body');
	var jArrText = jQuery.toJSON(arrayMs);
	creatHidden("jArrayMs", jArrText).appendTo(submitForm);
	var acId = jQuery("#ac_id").val();
	creatHidden("ac_id", acId).appendTo(submitForm);
	submitForm.submit();
}

//ms array process
function resetOrder() {
	for(var i = 0; i < arrayMs.length; i++)
		arrayMs[i].order = i + 1;
}

//if any error, return true
function checkAll() {
	resetOrder();
	for(var i = 0; i < arrayMs.length; i++) {
		 var tmp = arrayMs[i].name;
		 if(tmp == null || tmp.length < 1 || tmp.length > 50)
			 return i + 1;
		 tmp = arrayMs[i].mark;
		 if(tmp == null || isNaN(tmp) || tmp <= -1000 || tmp >= 1000)
			 return i + 1;
		 if(arrayMs[i].criteria == null)
			 arrayMs[i].criteria = "";
	}
	return -1;
}

//draw table function
function drawTable() {
	//if no data in arrayMs, skip the process
	if(arrayMs == null || arrayMs.length < 1)
		return;
	
	//draw to table
	var msTable = jQuery("table#ms_table");
	//clear the old data
	var intr = msTable.children('tbody').children('tr');
	if (intr.length > 1)
		intr.next().remove();
		
	//draw data
	for(var i = 0; i < arrayMs.length; i++) {
		var aRow = jQuery("<tr/>").appendTo(msTable);
		var ltd = jQuery("<td/>").appendTo(aRow);
		var rtd = jQuery("<td/>").appendTo(aRow);
		
		//inner table @ left td
		var innerTb = jQuery("<table width='100%' />").appendTo(ltd);
		//order
		var innRow = jQuery("<tr />").appendTo(innerTb);
		jQuery("<td>Order:</td>").appendTo(innRow);
		var inntd = jQuery("<td />").appendTo(innRow);
		createTextBox(("order_"+ (i+1)), arrayMs[i].order, true).appendTo(inntd);
		//name
		innRow = jQuery("<tr />").appendTo(innerTb);
		jQuery("<td>Name:</td>").appendTo(innRow);
		inntd = jQuery("<td />").appendTo(innRow);
		createTextBox(("name_"+ (i+1)), arrayMs[i].name, false).appendTo(inntd);
		jQuery("<span id=\"err_name_"+ (i+1)+ "\" style='color:red;'/>").appendTo(inntd);
		//criteria
		innRow = jQuery("<tr />").appendTo(innerTb);
		jQuery("<td>Criteria:</td>").appendTo(innRow);
		inntd = jQuery("<td />").appendTo(innRow);
		//textarea for criteria
		var innTarea = jQuery("<textarea rows=\"5\" cols=\"40\"/>");
		innTarea.attr("name", "criteria_" + (i+1));
		innTarea.attr("id", "criteria_" + (i+1));
		innTarea.val(arrayMs[i].criteria);
		innTarea.appendTo(inntd);
		//mark
		createTextBox(("mark_"+ (i + 1)), arrayMs[i].mark, false).appendTo(rtd);
		jQuery("<br /><span id=\"err_mark_"+ (i+1)+ "\" style='color:red;' />").appendTo(rtd);
		//Functions
		var ftd = jQuery("<td />").appendTo(aRow);
		jQuery('<a href="javascript:addBeforeThis('+ i+ ');">Add Before This</a><br />').appendTo(ftd);
		jQuery('<a href="javascript:removeThis('+ i+ ');">Remove This</a>').appendTo(ftd);
	}
	//add function link @ the end of table
	var lastRow = jQuery("<tr/>").appendTo(msTable);
	var lastCol = jQuery("<td colspan=\"3\"/>").appendTo(lastRow);
	jQuery('<a href="javascript:addAtEnd();">Add New Scheme</a><br />').appendTo(lastCol);
	jQuery('<a href="javascript:restartForm();">Undo All change</a>').appendTo(lastCol);
	//add change event
	jQuery('input[name^="name_"]').change(checkName);
	jQuery('input[name^="mark_"]').change(checkMark);
	
}

jQuery(document).ready(function() {
	orgArrayMs = arrayMs;
	arrayMs = cloneArray(orgArrayMs);
	drawTable();
});